<template>
    <div class="outer-order-page">
        <!-- 新增按钮 -->
        <el-button type="success" @click="goToAddPage">新增</el-button>
        
        <span style="font-size: 20px; margin-left: 20px; font-weight: bold">工艺列表</span>

        <!-- 工艺列表 -->
        <div class="table-container">
            <el-table 
                :data="planList" 
                stripe 
                ref="tableRef" 
                height="300"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="80"></el-table-column>
                <el-table-column prop="craftsmanshipCode" label="工艺编码" width="150"></el-table-column>
                <el-table-column prop="craftsmanshipName" label="工艺名称"></el-table-column>
                <el-table-column prop="leader" label="负责人"></el-table-column>
                <el-table-column prop="affiliation" label="所属部门" width="100"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
                            {{ scope.row.status === true ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="180"></el-table-column>
                <el-table-column label="操作" fixed="right" width="180">
                    <template #default="scope">
                        <!-- 编辑按钮，传递ID并跳转到编辑页面 -->
                        <el-button type="text" @click="goToEditPage(scope.row.craftsmanshipId)">编辑</el-button>
                        <el-button type="text" @click="deleteCraftsmanship(scope.row.craftsmanshipId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        
        <!-- 批量删除按钮 -->
        <el-button 
            type="danger" 
            @click="batchDelete" 
            :disabled="checkedIds.size === 0"
        >
            批量删除
        </el-button>
        
        <!-- 分页部分 -->
        <div class="demo-pagination-block" style="margin-top: 15px;">
            <el-pagination
                v-model:current-page="page.currentPage"
                v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import router from '@/router';

// API 地址
const API_URLS = {
    GET_CRAFTSMANSHIP_LIST: 'http://8.154.44.176:8000/f-read/api/GetProcess/GetCraftsmanship',
    DELETE_CRAFTSMANSHIP: 'http://8.154.44.176:8000/f-write/api/Process/DelCraftsmanship'
};

// 分页配置
const page = ref({
    currentPage: 1,
    pageSize: 20
});

// 总记录数
const total = ref({
    totalCount: 0
});

// 工艺列表数据
const planList = ref([]);

// 选中的工艺ID集合
const checkedIds = ref(new Set());

// 全选状态
const allChecked = ref(false);

// 半选状态
const indeterminate = computed(() => {
    return checkedIds.value.size > 0 && checkedIds.value.size < planList.value.length;
});

// 生命周期钩子：组件挂载后加载数据
onMounted(() => {
    fetchCraftsmanshipList();
});

// 获取工艺列表
const fetchCraftsmanshipList = async () => {
    try {
        const { data } = await axios.get(API_URLS.GET_CRAFTSMANSHIP_LIST, {
            params: {
                PageIndex: page.value.currentPage,
                PageSize: page.value.pageSize
            }
        });
        
        if (data.code === 200) {
            planList.value = data.data.list || [];
            total.value.totalCount = data.data.totalCount || 0;
            resetSelection(); // 重置选择状态
        } else {
            ElMessage.error(`获取工艺列表失败：${data.message}`);
        }
    } catch (error) {
        ElMessage.error('获取工艺列表失败，请检查网络连接');
        console.error('获取工艺列表错误:', error);
    }
};

// 处理选择变化
const handleSelectionChange = (selection) => {
    // 清空当前选中状态
    checkedIds.value.clear();
    // 添加新的选中项
    selection.forEach(item => checkedIds.value.add(item.craftsmanshipId));
    // 更新全选状态
    updateAllCheckedStatus();
};

// 更新全选状态
const updateAllCheckedStatus = () => {
    allChecked.value = checkedIds.value.size > 0 && checkedIds.value.size === planList.value.length;
};

// 重置选择状态
const resetSelection = () => {
    checkedIds.value.clear();
    allChecked.value = false;
};

// 分页相关方法
const handleSizeChange = (val) => {
    page.value.pageSize = val;
    fetchCraftsmanshipList();
};

const handleCurrentChange = (val) => {
    page.value.currentPage = val;
    fetchCraftsmanshipList();
};

// 跳转到新增页面
const goToAddPage = () => {
    router.push({ name: 'AddCraftsmanshipView' });
};

// 跳转到编辑页面，传递工艺ID
const goToEditPage = (craftsmanshipId) => {
    router.push({ 
        name: 'GetBYIdCraftsmanshipView', 
        query: { craftsmanshipId: craftsmanshipId } 
    });
};

// 删除单个工艺
const deleteCraftsmanship = async (craftsmanshipId) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除此工艺吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        
        const { data } = await axios.post(API_URLS.DELETE_CRAFTSMANSHIP, {
            craftsmanshipIds: craftsmanshipId.toString()
        });
        
        if (data.code === 200) {
            ElMessage.success('删除成功');
            fetchCraftsmanshipList(); // 刷新列表
        } else {
            ElMessage.error(`删除失败：${data.message}`);
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除过程中发生错误');
            console.error('删除工艺错误:', error);
        }
    }
};

// 批量删除工艺
const batchDelete = async () => {
    if (checkedIds.value.size === 0) {
        ElMessage.warning('请先选择要删除的工艺');
        return;
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${checkedIds.value.size} 条工艺吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        
        const ids = Array.from(checkedIds.value).join(',');
        const { data } = await axios.post(API_URLS.DELETE_CRAFTSMANSHIP, {
            craftsmanshipIds: ids
        });
        
        if (data.code === 200) {
            ElMessage.success('批量删除成功');
            fetchCraftsmanshipList(); // 刷新列表
            resetSelection(); // 重置选择状态
        } else {
            ElMessage.error(`批量删除失败：${data.message}`);
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除过程中发生错误');
            console.error('批量删除错误:', error);
        }
    }
};
</script>

<style scoped>
.table-container {
    margin-top: 20px;
}

.demo-pagination-block {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
}

.el-button + .el-button {
    margin-left: 10px;
}
</style>  